let util = {
	/**
	 * 根据code获取棋子类型
	 * @param {String} code 棋子code
	 */
	getPieceType: function(code) {
		return code.substr(code.indexOf("_") + 1, code.lastIndexOf("_") - 2);
	},
	/**
	 * 根据code获取棋子阵营
	 * @param {String} code 棋子code
	 */
	getPieceCamp: function(code) {
		return code.substring(0, 1);
	},
	/**
	 * 判断两个棋子code是否是同一阵营
	 */
	isSamePieceCamp: function(code1, code2) {
		return this.getPieceCamp(code1) == this.getPieceCamp(code2);
	},
	/**
	 * 根据位置获取棋子
	 */
	getPieceByCoo: function(pieces, coo) {
		let select = pieces.filter(p => p.coo[0] == coo[0] && p.coo[1] == coo[1]);
		return select != undefined ? select[0] : undefined;
	},
	/**
	 * 判断两个位置上的棋子是否是同一阵营
	 */
	isSamePieceCampByCoo: function(pieces, coo1, coo2) {
		let c1 = this.getPieceByCoo(pieces, coo1);
		let c2 = this.getPieceByCoo(pieces, coo2);
		if (c1 == undefined || c2 == undefined) {
			return false;
		}
		return this.getPieceCamp(c1.code) == this.getPieceCamp(c2.code);
	},
	/**
	 * 从棋盘中根据code获取该棋子对象
	 * @param {Array} pieces 棋盘的所有数据
	 * @param {String} code 棋子code
	 */
	getPiece: function(pieces, code) {
		let ps = pieces.filter(function(piece) {
			return piece && piece.code === code
		});

		if (ps && ps.length > 0) {

			return ps[0];
		}

		return null;
	},
	/**
	 * 给棋盘摆放一个棋子
	 * @param {Object} pieces 棋盘所有棋子
	 * @param {Object} piece 要摆放的棋子
	 * @param {Object} coo 要摆放的位置
	 */
	setPieceCoo: function(pieces, piece, coo) {
		if (this.getPieceByCoo(pieces, coo) != undefined) {

			console.warn("该位置已经存在棋子");
			throw "该位置已经存在棋子";
		} else {
			piece.coo = coo;
		}
	},
	/**
	 * 获取当前某个横坐标上的所有棋子(纵坐标相同的)
	 * @param {Array} pieces 当前棋盘数据
	 * @param {Number} y 当前棋子的纵坐标
	 */
	getXPiece: function(pieces, y) {
		return pieces.filter(function(piece) {
			return piece && piece.coo[1] == y;
		}).sort((o1, o2) => o1.coo[0] > o2.coo[0]);
	},
	/**
	 * 获取某个棋子纵坐标上的所有棋子(横坐标相等的)
	 * @param {Array} pieces 当前棋盘的数据
	 * @param {Number} x 当前棋子的横坐标
	 */
	getYPiece: function(pieces, x) {

		return pieces.filter(function(piece) {
			return piece && piece.coo[0] == x;
		}).sort((o1, o2) => o1.coo[1] > o2.coo[1]);
	},
	/**
	 * 获取一个棋子在横纵坐标上的距离最近的棋子
	 * @param {Array} pieces 当前棋盘的所有数据
	 * @param {Number} piece 当前棋子
	 */
	getAjoin: function(pieces, piece) {
		let x = piece.coo[0];
		let y = piece.coo[1];
		// 获取x轴上的所有棋子
		let xPieces = this.getXPiece(pieces, y);

		// 获取y轴上的所有棋子
		let yPieces = this.getYPiece(pieces, x);

		let numXIndex = xPieces.indexOf(xPieces.filter(x => x.code == piece.code)[0]);

		let numYIndex = yPieces.indexOf(xPieces.filter(y => y.code == piece.code)[0]);
		return {
			left: xPieces[numXIndex - 1],
			right: xPieces[numXIndex + 1],
			up: yPieces[numYIndex + 1],
			down: yPieces[numYIndex - 1]
		}
	}
}

export default util;
